//
//  ZLShadowView.swift
//  ZLUIKit_Example
//
//  Created by itzhaolei on 2021/8/26.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import UIKit

open class ZLShadowView: UIView {
    
    public var contentView: UIView = .init(frame: .zero)
    
    public override var backgroundColor: UIColor? {
        set {
            self.contentView.backgroundColor = newValue
        }
        get {
            return self.contentView.backgroundColor
        }
    }
    
    private var shadowColor: UIColor = .white
    private var cornerRadius: CGFloat = 0
    private var cornerRadiusDirection: UIRectCorner = .allCorners
    private var offset: CGSize = .init()
    private var opacity: CGFloat = 1.0
    
    /// 实例化阴影背景视图
    public convenience init(frame: CGRect?, color: UIColor, cornerRadius: CGFloat, cornerRadiusDirection: UIRectCorner, offset: CGSize = .zero, opacity: CGFloat = 0.7, action: Action?) {
        self.init(frame: frame ?? .zero)
        self.shadowColor = color
        self.cornerRadius = cornerRadius
        self.cornerRadiusDirection = cornerRadiusDirection
        self.offset = offset
        self.opacity = opacity
        self.contentView.frame = bounds
        self.contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(self.contentView)
        let path = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: .init(width: cornerRadius, height: cornerRadius)).cgPath
        self.layer.shadowColor = color.cgColor
        self.layer.shadowRadius = cornerRadius
        self.layer.shadowOpacity = Float(opacity)
        self.layer.shadowOffset = offset
        self.layer.shadowPath = path
        self.contentView.cornerRadius(cornerRadius, direction: cornerRadiusDirection)
        guard let action = action else { return }
        isUserInteractionEnabled = true
        addGestureRecognizer(UITapGestureRecognizer(target: action.target, action: action.action))
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        contentView.frame = bounds
        let path = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: .init(width: cornerRadius, height: cornerRadius)).cgPath
        layer.shadowPath = path
        contentView.cornerRadius(cornerRadius, direction: cornerRadiusDirection)
    }
    
}
